import { tools, ajax } from './ajax.js';

//#region 切换注册模式
// querySelectorAll获取一组对应css选择器的元素
let items = document.querySelectorAll('.list-group-item');
console.log('分组元素：', items);

function switchMode(mode) {
  if (mode == 1) {
    items[1].style.display = 'block';
    items[2].style.display = 'block';
    items[3].style.display = 'none';
    items[4].style.display = 'none';
  } else {
    items[1].style.display = 'none';
    items[2].style.display = 'none';
    items[3].style.display = 'block';
    items[4].style.display = 'block';
  }
}

switchMode(1);
// 切换按钮
let spswitch = document.querySelectorAll('.switch-box span');
spswitch[0].addEventListener('click', () => {
  switchMode(1);
});

spswitch[1].addEventListener('click', () => {
  switchMode(2);
});

//#endregion

//#region 邮箱注册的部分
let txt_email = document.getElementById('txt_email');
let txt_code = document.getElementById('txt_code');
let btnSendEmail = document.getElementById('btnSendEmail');
let btnReg = document.getElementById('btnReg');
let btnLogin = document.getElementById('btnLogin');

btnSendEmail.addEventListener('click', () => {
  ajax.post(
    '/tool/sendEmailCode',
    {
      email: txt_email.value,
    },
    (data) => {
      showToast(data.message);
    }
  );
});

btnReg.addEventListener('click', () => {
  ajax.post(
    '/user/auth/emailReg',
    {
      email: txt_email.value,
      info: txt_code.value,
    },
    (data) => {
      showToast(data.message);
    }
  );
});

btnLogin.addEventListener('click', () => {
  location.href = 'index.html';
});

//#endregion

//#region 用户注册的部分
let txt_username = document.getElementById('txt_username');
let txt_password = document.getElementById('txt_password');
let txt_nickname = document.getElementById('txt_nickname');
let btnUReg = document.getElementById('btnUReg');
let btnULogin = document.getElementById('btnULogin');

btnULogin.addEventListener('click', () => {
  location.href = 'index.html';
});

btnUReg.addEventListener('click', () => {
  let user = {
    username: txt_username.value,
    password: tools.md5(txt_password.value),
    nickname: txt_nickname.value,
  };

  ajax.post('/user/auth/reg', user, (data) => {
    showToast(data.message);
  });
});

//#endregion

//#region 信息弹出层的部分
let divToast = document.getElementById('divToast');
// querySelector是通过css选择器获取页面元素（只会返回一个）
let toastBody = document.querySelector('#divToast .toast-body');
// 创建toast对象
const toast = new bootstrap.Toast(divToast);

// 显示toast对话框
function showToast(message) {
  // 修改内容
  toastBody.innerHTML = message;
  // 显示
  toast.show();
}
//#endregion
